#!/usr/bin/env python
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')

#mysql - stats
def set_stats_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_groupbuy_stats')
    conn.connect()
    return conn
#mysql - open
def set_open_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_groupbuy_open')
    conn.connect()
    return conn

def execute(date):
    conn = set_stats_conn()
    op_conn = set_open_conn();
    #stat_table = "t_gbaction";
    
    query = "select groupbuy_id,sum(refund_order_count) from item_metrics where stat_date='%s' group by groupbuy_id having sum(refund_order_count)>2"%date
    items = conn.get_results(query)
    for item in items:
        gbid = item[0]
        order_count = item[1]
        
        query_tmp = "select sum(refund_order_count) from item_metrics where groupbuy_id=%s"%gbid
        items_tmp = conn.get_results(query_tmp)
        cnt = items_tmp[0][0]
        
        #print gbid,cnt
        del_sql = "delete from t_gbaction where rate=1 and groupbuyid=%s"%gbid
        op_conn.execute_sql(del_sql)
        
        sql = "insert into t_gbaction(groupbuyid,visit,sales,weight,rate) values(%s,1,%s,0,1) "%(gbid,cnt)
        #print sql
        try:
            op_conn.execute_sql(sql)
        except Exception,e:
            a=1
    

def main():

   #date = '2012-05-28'
   #execute(date)   
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute( stat_date) 
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)


if __name__=='__main__':
    main()